package com.example.meitao.tools;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils {

	/**指定url地址，下载图片等，返回的是字节数组
	 * @param path
	 * @return
	 */
	public static byte[] getDataBytes(String path){
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			if(conn.getResponseCode()==200){
				int length = conn.getContentLength();//数据的总字节数
				InputStream is = conn.getInputStream();
				byte[] arr = new byte[1024];
				int len;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while((len=is.read(arr))!=-1){
					baos.write(arr, 0, len);
				
					baos.flush();
				}
				return baos.toByteArray();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getDataStr(String path){
		String strJson = null;
		try {
			URL url = new URL(path);
			HttpURLConnection conn =(HttpURLConnection) url.openConnection();
			conn.connect();
			if(conn.getResponseCode()==200){
				InputStream is =  conn.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				String str;
				while((str=br.readLine())!=null){
					strJson =br.readLine();
				}
				br.close();
				return strJson;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}



}
